<template>
  <div class="app-container">
    <el-card class="form-card">
      <div slot="header" class="clearfix">
        <span class="form-title">{{ title }}</span>
        <el-button
          v-if="mode === 'create' && hasTempData"
          type="text"
          style="float: right; color: #909399;"
          @click="clearTempData"
        >
          清除临时数据
        </el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基本信息 -->
        <el-card class="section-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span class="section-title">基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="资产编号" prop="assetNo">
                <el-select
                  v-model="form.assetNo"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="handleAssetChange"
                  filterable
                  :disabled="mode === 'view'">
                  <el-option
                    v-for="asset in assetList"
                    :key="asset.assetNo"
                    :label="asset.assetNo"
                    :value="asset.assetNo" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="location">
                <el-input v-model="form.location" placeholder="请输入" :disabled="mode === 'view'" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类型" prop="assetType">
                <el-input v-model="form.assetType" placeholder="请选择资产类型" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="assetName">
                <el-select
                  v-model="form.assetNo"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="handleAssetNameChange"
                  filterable
                  :disabled="mode === 'view'">
                  <el-option
                    v-for="asset in assetList"
                    :key="asset.assetNo"
                    :label="asset.name"
                    :value="asset.assetNo" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="使用部门" prop="deptName">
                <el-select v-model="form.deptId" placeholder="请选择" style="width: 100%" :disabled="mode === 'view'">
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.deptId"
                    :label="dept.deptName"
                    :value="dept.deptId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 故障信息 -->
        <el-card class="section-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span class="section-title">故障信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发生时间" prop="occurrenceTime">
                <el-date-picker
                  v-model="form.occurrenceTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                  :default-time="new Date()"
                  :disabled="mode === 'view'"
                  :picker-options="pickerOptions"
                  @change="handleOccurrenceTimeChange" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报修人" prop="reporterId">
                <el-select v-model="form.reporterId" placeholder="请选择" style="width: 100%" :disabled="mode === 'view'">
                  <el-option
                    v-for="user in userList"
                    :key="user.userId"
                    :label="user.userName"
                    :value="user.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="故障类型" prop="faultTypeCode">
                <el-select v-model="form.faultTypeCode" placeholder="请选择" style="width: 100%" :disabled="mode === 'view'">
                  <el-option
                    v-for="type in faultTypeList"
                    :key="type.code"
                    :label="type.name"
                    :value="type.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急程度" prop="urgencyCode">
                <el-select v-model="form.urgencyCode" placeholder="请选择" style="width: 100%" :disabled="mode === 'view'">
                  <el-option
                    v-for="urgency in urgencyList"
                    :key="urgency.code"
                    :label="urgency.name"
                    :value="urgency.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="报修类型" prop="reportTypeCode">
                <el-select v-model="form.reportTypeCode" placeholder="请选择" style="width: 100%" :disabled="mode === 'view'">
                  <el-option
                    v-for="type in reportTypeList"
                    :key="type.code"
                    :label="type.name"
                    :value="type.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="故障描述" prop="faultDesc">
            <el-input
              v-model="form.faultDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入故障详细描述"
              maxlength="500"
              show-word-limit
              :disabled="mode === 'view'" />
          </el-form-item>
        </el-card>

        <!-- 故障图片 -->
        <el-card class="section-card">
          <div slot="header" class="clearfix">
            <span class="section-title">故障图片</span>
            <span class="upload-tip">最多上传5张，单张不大于2MB</span>
          </div>
          <el-upload
            action="#"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :limit="5"
            accept="image/*"
            :disabled="mode === 'view'">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-card>
      </el-form>

      <div class="form-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="info" @click="handleTempSave" v-if="mode !== 'view'">临时保存</el-button>
        <el-button type="primary" @click="submitForm" v-if="mode !== 'view'">提交</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { addReportOrder, updateReportOrder, getReportOrder } from '@/api/repair/reportOrder'
import { listAsset } from '@/api/asset/asset'
import { listDept } from '@/api/system/dept'
import { listFaultType } from '@/api/dict/faultType'
import { listLevel } from '@/api/dict/level'
import { listReportType } from '@/api/dict/reportType'

export default {
  name: 'OrderForm',
  props: {
    mode: {
      type: String,
      default: 'create'
    },
    orderId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        reportNo: null,
        assetNo: null,
        assetName: null,
        assetType: null,
        location: null,
        deptId: null,
        occurrenceTime: new Date(),
        reporterId: null,
        faultTypeCode: null,
        urgencyCode: null,
        reportTypeCode: null,
        faultDesc: null,
        status: 'DRAFT'
      },
      pickerOptions: {
        // 禁用今天之后的日期
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      rules: {
        assetNo: [
          { required: true, message: '请选择资产编号', trigger: 'change' }
        ],
        assetName: [
          { required: true, message: '请选择资产名称', trigger: 'change' }
        ],
        occurrenceTime: [
          { required: true, message: '请选择发生时间', trigger: 'change' },
          {
            validator: this.validateOccurrenceTime,
            trigger: 'change'
          }
        ],
        reporterId: [
          { required: true, message: '请选择报修人', trigger: 'change' }
        ],
        faultTypeCode: [
          { required: true, message: '请选择故障类型', trigger: 'change' }
        ],
        urgencyCode: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ],
        reportTypeCode: [
          { required: true, message: '请选择报修类型', trigger: 'change' }
        ],
        faultDesc: [
          { required: true, message: '请输入故障描述', trigger: 'blur' }
        ]
      },
      assetList: [],
      deptList: [],
      userList: [
        { userId: "1", userName: "杨文浩" },
        { userId: "2", userName: "张三" },
        { userId: "3", userName: "李四" },
        { userId: "4", userName: "王五" }
      ],
      faultTypeList: [],
      urgencyList: [],
      reportTypeList: [],
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  computed: {
    title() {
      return this.mode === 'create' ? '添加报修' :
        this.mode === 'edit' ? '编辑报修' : '报修单'
    },
    hasTempData() {
      return !!localStorage.getItem('tempRepairOrder')
    }
  },
  watch: {
    orderId: {
      immediate: true,
      handler(newVal) {
        if (this.mode !== 'create' && newVal) {
          this.getDetail(newVal)
        }
      }
    }
  },
  created() {
    this.getAssetList()
    this.getDeptList()
    this.getFaultTypeList()
    this.getUrgencyList()
    this.getReportTypeList()
    // 如果是创建模式，检查是否有临时保存的数据
    if (this.mode === 'create') {
      this.loadTempData()
    }
  },
  methods: {
    handleOccurrenceTimeChange(value) {
      this.validateOccurrenceTime(null, value, () => {});
    },

    validateOccurrenceTime(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择发生时间'));
        return;
      }

      const selectedTime = new Date(value);
      const now = new Date();

      if (selectedTime > now) {
        // 如果选择的日期超过当前时间，清除并提示
        this.form.occurrenceTime = new Date();
        callback(new Error('发生时间不能晚于当前时间，请重新选择'));
      } else {
        callback();
      }
    },
    
    async getAssetList() {
      try {
        const response = await listAsset({ pageNum: 1, pageSize: 1000 })
        this.assetList = response.rows
      } catch (error) {
        console.error('获取资产列表失败:', error)
        this.$modal.msgError('获取资产列表失败，请重试')
      }
    },
    async getDeptList() {
      try {
        const response = await listDept({ pageSize: 1000 })
        this.deptList = response.rows
        console.log('部门列表:', response)
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.$modal.msgError('获取部门列表失败，请重试')
      }
    },
    async getFaultTypeList() {
      try {
        const response = await listFaultType({ pageSize: 1000 })
        this.faultTypeList = response.rows
      } catch (error) {
        console.error('获取故障类型列表失败:', error)
        this.$modal.msgError('获取故障类型列表失败，请重试')
      }
    },
    async getUrgencyList() {
      try {
        const response = await listLevel({ pageSize: 1000 })
        this.urgencyList = response.rows
      } catch (error) {
        console.error('获取紧急程度列表失败:', error)
        this.$modal.msgError('获取紧急程度列表失败，请重试')
      }
    },
    async getReportTypeList() {
      try {
        const response = await listReportType({ pageSize: 1000 })
        this.reportTypeList = response.rows
      } catch (error) {
        console.error('获取报修类型列表失败:', error)
        this.$modal.msgError('获取报修类型列表失败，请重试')
      }
    },
    handleAssetChange(assetNo) {
      const asset = this.assetList.find(item => item.assetNo === assetNo)
      if (asset) {
        this.form.assetName = asset.assetName
        this.form.assetType = asset.assetType
        this.form.location = asset.location
        this.form.deptId = asset.deptId
      } else {
        // 当选择为空时，清空相关字段
        this.form.assetName = null
        this.form.assetType = null
        this.form.location = null
        this.form.deptId = null
      }
    },
    handleAssetNameChange(assetName) {
      const asset = this.assetList.find(item => item.assetName === assetName)
      if (asset) {
        this.form.assetNo = asset.assetNo
        this.form.assetType = asset.assetType
        this.form.location = asset.location
        this.form.deptName = asset.deptName
      } else {
        // 当选择为空时，清空相关字段
        this.form.assetNo = null
        this.form.assetType = null
        this.form.location = null
        this.form.deptId = null
      }
    },
    async getDetail(reportNo) {
      try {
        const response = await getReportOrder(reportNo)
        this.form = {
          ...response.data,
          occurrenceTime: response.data.occurrenceTime ? new Date(response.data.occurrenceTime) : new Date()
        }
        // 确保资产相关信息正确设置
        if (this.form.assetNo) {
          this.handleAssetChange(this.form.assetNo)
        }
      } catch (error) {
        console.error('获取报修单详情失败:', error)
        this.$modal.msgError('获取详情失败，请重试')
      }
    },
    // 加载临时保存的数据
    loadTempData() {
      try {
        const tempData = localStorage.getItem('tempRepairOrder')
        if (tempData) {
          const parsedData = JSON.parse(tempData)
          this.form = {
            ...this.form,
            ...parsedData,
            reportNo: null,
            occurrenceTime: new Date()
          }
        }
      } catch (error) {
        console.error('加载临时数据失败:', error)
      }
    },
    clearTempData() {
      localStorage.removeItem('tempRepairOrder')
      this.form = {
        reportNo: null,
        assetNo: null,
        assetName: null,
        assetType: null,
        location: null,
        deptId: null,
        occurrenceTime: new Date(),
        reporterId: null,
        faultTypeCode: null,
        urgencyCode: null,
        reportTypeCode: null,
        faultDesc: null,
        status: 'DRAFT'
      }
      this.$modal.msgSuccess('已清除临时数据')
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleBack() {
      this.$emit('cancel')
    },
    handleTempSave() {
      // 临时保存不进行表单验证，直接保存当前填写的数据
      const formData = { ...this.form }

      try {
        // 使用本地存储模拟临时保存
        localStorage.setItem('tempRepairOrder', JSON.stringify(formData))
        this.$modal.msgSuccess('临时保存成功')
      } catch (error) {
        console.error('临时保存失败:', error)
        this.$modal.msgError('临时保存失败，请重试')
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = { ...this.form }
          if (this.mode === 'edit') {
            updateReportOrder(formData).then(() => {
              this.$modal.msgSuccess('修改成功')
              // 提交成功后清除临时保存的数据
              localStorage.removeItem('tempRepairOrder')
              this.$emit('save-success')
            }).catch(error => {
              console.error('修改失败:', error)
              this.$modal.msgError('修改失败，请重试')
            })
          } else {
            addReportOrder(formData).then(() => {
              this.$modal.msgSuccess('新增成功')
              // 提交成功后清除临时保存的数据
              localStorage.removeItem('tempRepairOrder')
              this.$emit('save-success')
            }).catch(error => {
              console.error('新增失败:', error)
              this.$modal.msgError('新增失败，请重试')
            })
          }
        } else {
          this.$modal.msgError('请完善必填信息后再提交')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.form-card {
  margin: 20px;
}
.form-title {
  font-size: 18px;
  font-weight: bold;
}
.section-title {
  font-weight: bold;
  font-size: 16px;
}
.upload-tip {
  float: right;
  font-size: 12px;
  color: #909399;
}
.section-card {
  margin-bottom: 20px;
}
.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>
